package com.security.hikapp.network.response;

import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.security.hikapp.network.exception.ApiException;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.ObservableTransformer;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * 获取IReponse后判断请求结果，并获取data返回
 * Observable<IResponse<T>> --》Observable<T>
 * 可以自己实现，这里只是提供统一封装的思路
 */
public class ResponseTransformer<T> implements ObservableTransformer<IResponse<T>, IResponse<T>>, LifecycleObserver {

    private CompositeDisposable compositeDisposable;

    public ResponseTransformer(CompositeDisposable compositeDisposable){
        this.compositeDisposable = compositeDisposable;
    }

    public ResponseTransformer(){
    }


    @Override
    public ObservableSource<IResponse<T>> apply(Observable<IResponse<T>> upstream) {
        return upstream.doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Throwable {
                if (compositeDisposable != null) {
                    compositeDisposable.add(disposable);
                }
            }
        }).onErrorResumeNext(new Function<Throwable, ObservableSource<? extends IResponse<T>>>() {
            @Override
            public ObservableSource<? extends IResponse<T>> apply(Throwable throwable) throws Throwable {
                return Observable.error(ApiException.handleException(throwable));
            }
        }).flatMap(new Function<IResponse<T>, ObservableSource<IResponse<T>>>() {
            @Override
            public ObservableSource<IResponse<T>> apply(IResponse<T> response) throws Throwable {
//                if (response.isSuccess()) {
                    return Observable.just(response);
//                }
//                return Observable.error(new ApiException(response.getStatus(), response.getMessage()));
            }
        }).subscribeOn(Schedulers.io())//指定事件产生的线程（请求的线程）
          .observeOn(AndroidSchedulers.mainThread());//指定事件处理的线程（响应的线程）;
    }
    //实现对rxjava生命周期的管理，防止内存泄漏
    public static <T> ResponseTransformer<T> obtain(LifecycleOwner lifecycleOwner){
        ResponseTransformer<T> transformer = new ResponseTransformer<>();
        lifecycleOwner.getLifecycle().addObserver(transformer);
        return transformer;
    }

    public static <U> ResponseTransformer<U> obtain(CompositeDisposable compositeDisposable){
        return new ResponseTransformer<>(compositeDisposable);
    }

    public static <U> ResponseTransformer<U> obtain(){
        return new ResponseTransformer<>();
    }
}
